package star.oath.framework.generate.template;

import star.oath.framework.generate.CodeGenerator;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.regex.Pattern;

public class MapperXmlTemplate {
    /**
     * 根据实体类全限定名生成对应的 Mapper XML 文件，与 Mapper 接口放在同一目录
     * @param fullyQualifiedEntityName
     */
    public void generateMapperXml(String fullyQualifiedEntityName) {
        if (fullyQualifiedEntityName == null || fullyQualifiedEntityName.trim().isEmpty()) {
            throw new IllegalArgumentException("实体类全限定名不能为空");
        }

        // 1. 拆分类名和包名
        int lastDot = fullyQualifiedEntityName.lastIndexOf('.');
        if (lastDot == -1) {
            throw new IllegalArgumentException("无效的全限定类名: " + fullyQualifiedEntityName);
        }

        String entityPackageName = fullyQualifiedEntityName.substring(0, lastDot);
        String className = fullyQualifiedEntityName.substring(lastDot + 1);

        // 2. 校验类名
        if (!CodeGenerator.VALID_CLASS_NAME.matcher(className).matches()) {
            throw new IllegalArgumentException("非法的类名: " + className);
        }

        // 3. 确保在 .model 包下
        if (!entityPackageName.endsWith(".model")) {
            throw new IllegalArgumentException("实体类必须位于 .model 包下，当前包: " + entityPackageName);
        }

        // 4. 推导 Mapper 接口的全限定名
        String mapperPackageName = entityPackageName.substring(0, entityPackageName.length() - "model".length()) + "mapper";
        String mapperClassName = className + "Mapper";
        String mapperFullyQualifiedName = mapperPackageName + "." + mapperClassName;

        // 5. 构建 XML 内容
        String xmlContent = String.format(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                        "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n" +
                        "<mapper namespace=\"%s\">\n" +
                        "</mapper>\n",
                mapperFullyQualifiedName
        );

        // 6. 构建 XML 文件路径（与 Mapper 接口同目录）
        String mapperDirPath = CodeGenerator.SRC_MAIN_JAVA + mapperPackageName.replace('.', '/');
        Path xmlDir = Paths.get(mapperDirPath);
        try {
            Files.createDirectories(xmlDir);
            Path xmlFile = xmlDir.resolve(mapperClassName + ".xml");
            Files.write(xmlFile, xmlContent.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
            System.out.println("✅ Mapper XML 已生成: " + xmlFile.toAbsolutePath());
        } catch (IOException e) {
            System.err.println("❌ 生成 Mapper XML 失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}